package top.frsf.web.controller.system;

import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import top.frsf.common.constant.Constants;
import top.frsf.common.core.domain.AjaxResult;
import top.frsf.common.core.domain.entity.SysMenu;
import top.frsf.common.core.domain.entity.SysUser;
import top.frsf.common.core.domain.model.LoginBody;
import top.frsf.common.core.domain.model.UserBindPhone;
import top.frsf.common.utils.SecurityUtils;
import top.frsf.common.utils.StringUtils;
import top.frsf.common.utils.sign.Base64;
import top.frsf.framework.web.service.SysLoginService;
import top.frsf.framework.web.service.SysPermissionService;
import top.frsf.manage.domain.dto.PhoneNumberRequest;
import top.frsf.manage.domain.dto.PhoneNumberResponse;
import top.frsf.manage.service.IWeChatService;
import top.frsf.quartz.util.AbstractQuartzJob;
import top.frsf.system.domain.dto.WxLoginBody;
import top.frsf.system.service.ISysMenuService;
import top.frsf.web.core.config.WxAppConfig;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.Valid;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private WxAppConfig wxAppConfig;

    @Autowired
    private IWeChatService weChatService;

    private static final Logger log = LoggerFactory.getLogger(SysLoginController.class);
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    @PostMapping("/bindPhoneNumber")
    public AjaxResult bindPhoneNumber(@RequestBody UserBindPhone userBindPhone) {
        loginService.bindPhoneNumber(userBindPhone.getOpenId(),userBindPhone.getPhoneNumber());
        return AjaxResult.success();
    }

    /**
     * 微信登录
     * @param wxLoginBody
     * @return
     */
    @PostMapping("/wxLogin")
    public AjaxResult wxLogin(@RequestBody WxLoginBody wxLoginBody) {
        // 2. 向微信服务器发送请求
        log.info(JSONObject.toJSONString(wxLoginBody));
        RestTemplate restTemplate = new RestTemplate();
        String code = wxLoginBody.getCode();
        //向微信服务器发送请求获取用户信息
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppConfig.getAppid() + "&secret=" + wxAppConfig.getAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";

        String res = restTemplate.getForObject(url, String.class);
        log.info("微信登录返回结果：{}", res);
        JSONObject jsonObject = JSONObject.parseObject(res);
         if(jsonObject.containsKey("errcode")){
            return AjaxResult.error("微信登录失败！"+jsonObject.getString("errmsg"));
         }
        //获取session_key和openid
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
//        openid="oobo-16Mt5q4Ysjm4lWQe1H9lMH0";

        if (StringUtils.hasText(openid)) {
            //如果解析成功,获取token
            String token = loginService.wxLogin(openid);
            SysUser sysUser = loginService.selectUserByOpenId(openid);
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            ajax.put("openid", openid);
            if (sysUser != null) {
                ajax.put("phonenumber", sysUser.getPhonenumber());
            }else{
                ajax.put("phonenumber", "");
            }
            return ajax;
        } else {
            return AjaxResult.error("微信登录失败！");
        }
    }

    /**
     * 获取用户手机号接口
     */
    @PostMapping("/phoneNumber")
    public AjaxResult getPhoneNumber(@Valid @RequestBody PhoneNumberRequest request) {
        try {
            PhoneNumberResponse response = weChatService.getPhoneNumber(request.getCode());

            if (response != null && response.getErrcode() == 0 &&
                    response.getPhone_info() != null) {
                String phoneNumber = response.getPhone_info().getPhoneNumber();

                // 这里可以添加业务逻辑，如保存手机号到用户信息等
                // userService.bindPhoneNumber(currentUserId, phoneNumber);

                return AjaxResult.success(phoneNumber);
            } else {
                String errorMsg = response != null ? response.getErrmsg() : "获取手机号失败";
                return AjaxResult.error(-1, errorMsg);
            }
        } catch (Exception e) {
            return AjaxResult.error(-1, e.getMessage());
        }
    }
    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
